axios.defaults.baseURL="http://localhost:8080";
Vue.prototype.$http=axios;
//======================axios的前置拦截器【拦截调用后端的请求====================//
axios.interceptors.request.use(res=>{
    let token = localStorage.getItem("token");
    if(token){
        res.headers["token"] = token;
    }
    return res;
},error => {
    Promise.reject(error)
})
//======================axios的前置拦截器【拦截调用后端的请求】====================//

//======================axios的后置拦截器【处理后台登录拦截的结果】====================//
axios.interceptors.response.use(res => {
    //后端响应的是没有登录的信息
    if (false === res.data.success && "noLogin" === res.data.msg) {
        localStorage.removeItem("token");
        localStorage.removeItem("logininfo");
        //跳到鄧麗頁面
        location.href="login.html";
        /*router.push({path: '/login'});*/
    }  if (false === res.data.success && "timeout" === res.data.msg) {
        localStorage.removeItem("token");
        localStorage.removeItem("logininfo");
        alert("登录过期");
        location.href="login.html";
    }
    return res;
},error => {
    Promise.reject(error)
})
//======================axios的后置拦截器【处理后台登录拦截的结果】====================//

//3. 静态资源拦截器

//3.静态资源拦截器：拦截不发送axios请求的页面【登录之后才能访问】
//如果访问的不是login.html 或 register.html,都要判断是否登录【logininfo】
let url = location.href; //localhost/index.html
//如果访问的不是login.html 并且 register.html,都要判断是否登录【logininfo】
if(url.indexOf("login.html")==-1
    && url.indexOf("register.html")==-1
    && url.indexOf("binder.html")==-1
    && url.indexOf("callback.html")==-1){//访问其他页面
    var logininfoStr = localStorage.getItem("logininfo");
    //如果logininfoStr没有值 - 没有登录
    if(!logininfoStr){
        //跳转到登录页面
        location.href = "login.html";
    }
}


//封装公用方法 - 将字符串的参数解析为json对象
function parseUrlParams2Obj(url) {
    let paramStr = url.substring(url.indexOf("?")+1);//xxx?code=xxx&state=1
    let paramArr = paramStr.split("&");
    let paramObj = {};
    for(let i = 0;i<paramArr.length;i++){
        let paramTemp = paramArr[i];
        let paramName = paramTemp.split("=")[0];//code state
        let paramValue= paramTemp.split("=")[1];//xxx   1
        paramObj[paramName] = paramValue;
        console.log(paramObj[paramName])
    }
    return paramObj;
}

/*
router.beforeEach((to, from, next) => {
    if (to.path == '/login' || to.path == '/register' ) {
        next();
    }else{//访问其他页面 - 判断是否登录过 - logininfo
        let logininfo = JSON.parse(localStorage.getItem('logininfo'));
        if(logininfo){
            next();
        }else{//访问的不是登录页面，页不是注册页面。没有登录
            next({ path: '/login' })
        }
    }
})*/
